package ltd.newbee.mall.service.impl;

import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.api.mall.param.WxPayParam;
import ltd.newbee.mall.api.mall.vo.NewBeeMallOrderDetailVO;
import ltd.newbee.mall.util.Util;
import net.sf.json.JSONObject;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
 * @program: openPlatform
 * @description: 公众号支付
 */
@Slf4j
@Service
public class PublicPay {

    static String timestamp;
    static String nonce;
    static String authorization;

    @Value("${wxpay.url}")
    private String url;

    @Value("${wxpay.appId}")
    private String appId;
    @Value("${wxpay.appKey}")
    private String appKey;
    @Value("${wxpay.instMid}")
    private String instMid;

    @Value("${wxpay.mid}")
    private String mid;

    @Value("${wxpay.tid}")
    private String tid;

    @Value("${wxpay.notifyUrl}")
    private String notifyUrl;

    @Value("${wxpay.returnUrl}")
    private String returnUrl;

    public static void main(String[] args) throws Exception {
        //pay();
        //query();
        //refund();
    }


    public String pay(String merOrderId, WxPayParam wxPayParam, NewBeeMallOrderDetailVO newBeeMallOrderDetailVO) throws Exception {


        timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        nonce = UUID.randomUUID().toString().replace("-", "");
        JSONObject json = new JSONObject();
        json.put("instMid", instMid); // 业务类型
        json.put("mid", mid); // 商户号
        json.put("tid", tid);    // 终端号
        BigDecimal payTotalPrice = newBeeMallOrderDetailVO.getTotalPrice().multiply(new BigDecimal(100));
        json.put("totalAmount", payTotalPrice);      // 支付总金额
        json.put("merOrderId", merOrderId); // 商户订单号
        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));    // 报文请求时间
        json.put("notifyUrl", notifyUrl + "?orderNo=" + wxPayParam.getOrderNo() + "&payType=2");
        json.put("returnUrl", returnUrl + "?orderNo=" + wxPayParam.getOrderNo());

        // 分账部分
//        json.put("divisionFlag", true); // 分账标记
//        json.put("platformAmount", 10); // 平台商户分账金额
//        ArrayList subOrders = new ArrayList<>();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("mid", "子商户号");
//        jsonObject.put("totalAmount", 10);
//        subOrders.add(jsonObject);
//        json.put("subOrders", subOrders);
        log.info("请求报文:\n" + json);
        String signatrue = Util.getOpenBodySig(appId, appKey, timestamp, nonce, json.toString());
        //GET 请求形式拼接认证方式
        String param = "authorization=OPEN-FORM-PARAM" + "&appId=" + appId + "&timestamp=" + timestamp + "&nonce=" + nonce + "&content=" + URLEncoder.encode(json.toString(), "UTF-8") + "&signature=" + URLEncoder.encode(signatrue, "UTF-8");
        log.info("URL:\n" + url + "/webpay/pay?" + param);
        String parUrl = url + "/webpay/pay?" + param;
        return parUrl;
    }

    /*public static void pay() throws Exception {
        timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        nonce = UUID.randomUUID().toString().replace("-", "");
        JSONObject json = new JSONObject();
        json.put("instMid", "YUEDANDEFAULT"); // 业务类型
        json.put("mid", "898201612345678"); // 商户号
        json.put("tid", "88880001");    // 终端号
        json.put("totalAmount", "1");      // 支付总金额
        json.put("merOrderId", "103A"+Util.getMerchantOrderId()); // 商户订单号
        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));    // 报文请求时间

        *//* 分账部分 *//*
//        json.put("divisionFlag", true); // 分账标记
//        json.put("platformAmount", 10); // 平台商户分账金额
//        ArrayList subOrders = new ArrayList<>();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("mid", "子商户号");
//        jsonObject.put("totalAmount", 10);
//        subOrders.add(jsonObject);
//        json.put("subOrders", subOrders);
        System.out.println("请求报文:\n"+json);
        String signatrue = Util.getOpenBodySig(appId, appKey, timestamp, nonce, json.toString());
        String url = "https://test-api-open.chinaums.com/v1/netpay/webpay/pay";
        //GET 请求形式拼接认证方式
        String param="authorization=OPEN-FORM-PARAM" + "&appId=" + appId + "&timestamp=" + timestamp + "&nonce=" + nonce + "&content=" + URLEncoder.encode(json.toString(), "UTF-8") + "&signature=" + URLEncoder.encode(signatrue, "UTF-8");
        System.out.println("URL:\n" + url + "?" + param);
    }*/


    //支付查询
    public void query() throws Exception {
        timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        nonce = UUID.randomUUID().toString().replace("-", "");
        JSONObject json = new JSONObject();
        json.put("instMid", "YUEDANDEFAULT"); // 业务类型
        json.put("mid", "898201612345678"); // 商户号
        json.put("tid", "88880001");    // 终端号

        json.put("merOrderId", "103A202509231657358246429135"); // 商户订单号
        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));    // 报文请求时间

        System.out.println("请求报文:\n" + json);
        String signatrue = Util.getOpenBodySig(appId, appKey, timestamp, nonce, json.toString());
        String url = "https://test-api-open.chinaums.com/v1/netpay/query";
        //url = "https://test-api-open.chinaums.com/v1/netpay/refund-query";
        //post 请求形式拼接认证方式
        authorization = "OPEN-BODY-SIG AppId=" + "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + signatrue + "\"";
        System.out.println("请求头：" + authorization);
        String send = Util.send(url, json.toString(), authorization);
        System.out.println("返回结果:\n" + send);
    }


    //退款
    public String refund(String refundNo, NewBeeMallOrderDetailVO newBeeMallOrderDetailVO) throws Exception {
        timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        nonce = UUID.randomUUID().toString().replace("-", "");
        JSONObject json = new JSONObject();
        json.put("instMid", instMid); // 业务类型
        json.put("mid", mid); // 商户号
        json.put("tid", tid);    // 终端号

        json.put("merOrderId", newBeeMallOrderDetailVO.getPayNo()); // 商户订单号
        json.put("refundOrderId", refundNo); // 退货订单号
        json.put("refundAmount", 1); // 商户订单号

        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));    // 报文请求时间

        log.info("请求报文:\n" + json);
        String signatrue = Util.getOpenBodySig(appId, appKey, timestamp, nonce, json.toString());
        String refundUrl = url + "/refund";
        //post 请求形式拼接认证方式
        authorization = "OPEN-BODY-SIG AppId=" + "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + signatrue + "\"";
        log.info("请求头：" + authorization);
        String send = Util.send(refundUrl, json.toString(), authorization);
        log.info("返回结果:\n" + send);
        return send;
    }


}
